<!-- 在办文书 -->
<template>
	<view class="content">
		<view class="navs_head">
			<text>在办文书</text>
			<image src="../../static/img/onLineNavBg.png" mode=""></image>
			<view class="tabLoopList">
				<view
					class="loopItem"
					v-for="(item, index) in bookTypeList"
					:key="item.id"
					:class="{ item_active: itemActive === index }"
					@click="checkItem(index)"
				>
					{{ item.value }}
				</view>
			</view>
		</view>
		<!-- tab切换栏 -->
		<view class="tabsList">
			<view
				v-for="(item, index) in tabsList"
				:key="index"
				:class="{ tabActive: index === tabsActive }"
				@click="checkTabs(index)"
			>
				{{ item.value }}
			</view>
		</view>
		<!-- 日期选择器-->
		<view class="cardList">
			<DatePicker @changeTime="changeTime" />
			<custom-pagination
				v-model:list="cardList"
				v-model:loading="loading"
				v-model:no-more-data="noMoreData"
				@refresh="refreshList"
				@load-more="loadMoreList"
			>
				<template #list>
					<CardWrap v-for="(item, index) in cardList" :key="index">
						<view class="card_title">
							<view>
								{{ stateFilter(item.state) }}时间：
								<text>{{tabsActive === 0 ? item.createTime: tabsActive === 1 ? (item.signTime || item.firstViewTime) : item.signTime }}</text>
							</view>
							<view class="reciver" v-if="tabsActive === 1">
								发送时间：{{ item.createTime }}
							</view>
							<view
								class="feedBack"
								v-if="tabsActive === 2"
								:class="statesBgColor"
							>
								{{ expirationDate(item.feedbackExpireTime) }}
							</view>
						</view>
						<view
							class="card_content"
							:class="{ specialDire: tabsActive !== 0 }"
						>
							<view class="left">
								<text>{{filterDocument(item.deliveryType)}}</text>
								<text>{{item.deliveryDeptName}}-{{ item.unitName }}-{{item.contact}}</text>
							</view>
							<view class="right">
								<view class="reciver" v-if="tabsActive === 2">
									发送时间：{{item.createTime}}
								</view>
								<view class="seeDetailBtn" @click="seeDetail(item.id)">
									{{ tabsActive === 3 ? '查看反馈' : '查看' }}
								</view>
					<!-- 			<view
									class="downLoad"
									v-if="[1, 3].includes(tabsActive)"
									@click="downLoad(item.proofServiceUrl, item.recipientDept)"
								>
									<image
										src="../../static/icon/downLoad_blue.png"
										mode=""
									></image
									>下载
								</view> -->
							</view>
						</view>
					</CardWrap>
				</template>
			</custom-pagination>
		</view>
	</view>
</template>

<script setup>
import { reactive, ref } from 'vue'
import { seeDocumentList } from '@/api/file.js'
import { onLoad, onHide, onShow } from '@dcloudio/uni-app'
const bookTypeList = ref([
	{ id: 1, value: '检察建议书' },
	{ id: 2, value: '检察意见书' },
	{ id: 3, value: '磋商书' },
])
const itemActive = ref(0)
const checkItem = (index) => {
	itemActive.value = index
	refreshList()
}
const tabsList = [
	{ id: 1, value: '待签收' },
	{ id: 2, value: '已签收' },
	{ id: 3, value: '待反馈' },
	{ id: 4, value: '已反馈' },
]
const tabsActive = ref(0)
const checkTabs = (index) => {
	tabsActive.value = index
	refreshList()
}
onShow(() => {
	uni.$on('accessState', ({ title }) => {
		tabsActive.value = tabsList.findIndex((val) => {
			return val.value === title
		})
		refreshList()
	})
})
onHide(() => {
	uni.$off('accessState', () => {
		tabsActive.value = 0
	})
})
const stateFilter = () => {
	let reciverName = ''
	switch (tabsActive.value) {
		case 0:
			reciverName = '发送'
			break
		case 3:
			reciverName = '反馈'
			break
		default:
			reciverName = '签收'
	}
	return reciverName
}
// 查看详情
const seeDetail = (id) => {
	if (tabsActive.value === 3) {
		uni.navigateTo({
			url: `/pages/seeFeedBack/seeFeedBack?deliveryId=${id}`,
		})
	} else if ([0, 1, 2].includes(tabsActive.value)) {
		uni.navigateTo({
			url: `/pages/fileList/fileList?type=${tabsActive.value}&id=${id}`,
		})
	}
}

// 分页功能区域代码
const cardList = ref([]) //分页列表
const loading = ref(false) //数据加载中
const noMoreData = ref(false) //暂无更多数据
// 获取文书列表
const postData = reactive({
	deliveryType: '', //送达文件类型（1 检察建议书 2 检察意见书 3 磋商文书）
	acceptState: '', //接收状态（0待签收 1已签收 2待反馈 3已反馈）
	startTime: '',
	endTime: '',
	pageNum: 1,
	pageSize: 10,
})
const getPageList = async (refresh = false) => {
	loading.value = true
	postData.deliveryType = itemActive.value + 1
	postData.acceptState = tabsActive.value
	try {
		const { code, data: res } = await seeDocumentList(postData)
		if (code === 200) {
			const { total, list } = res
			if (refresh) {
				cardList.value = list
			} else {
				cardList.value = [...cardList.value, ...list]
			}
			noMoreData.value = total <= postData.pageSize * postData.pageNum
			if (!noMoreData.value) {
				postData.pageNum++
			}
		}
	} catch (e) {
		//TODO handle the exception
		return Promise.reject('获取数据失败', e)
	} finally {
		loading.value = false
	}
}
const refreshList = async () => {
	postData.pageNum = 1
	noMoreData.value = false
	await getPageList(true)
}
const loadMoreList = async () => {
	if (!noMoreData.value) {
		await getPageList(false)
	}
}
const changeTime = (val) => {
	postData.startTime = val[0]
	postData.endTime = val[1]
	refreshList()
}
// 下载
const downLoad = (url, name) => {
	// #ifdef H5
	const fileType = url.split('.').pop()
	console.log('文件类型', fileType)
	uni.downloadFile({
		url,
		success(res) {
			console.log('下载文件成功！', res)
			if (res.statusCode === 200) {
				const tempFilePath = res.tempFilePath
				// #ifdef H5
				// H5环境下，创建下载链接
				const a = document.createElement('a')
				a.href = tempFilePath
				a.download = `${name}.${fileType}` // 替换为实际的文件名
				document.body.appendChild(a)
				a.click()
				document.body.removeChild(a)
				uni.hideLoading()
				uni.showToast({ title: '下载完成', icon: 'success' })
				// #endif
			}
		},
	})
	// #endif
}
// 计算间隔时间
const statesBgColor = ref('')
const expirationDate = (date) => {
	const targetDate = new Date(date)
	// 获取当前日期
	const currentDate = new Date()
	// 计算时间差（以毫秒为单位）
	const timeDifference = targetDate - currentDate
	// 将时间差转换为天数（1天 = 24 * 60 * 60 * 1000 毫秒）
	const daysUntilExpiration = Math.ceil(timeDifference / (24 * 60 * 60 * 1000))
	if (daysUntilExpiration < 0) {
		statesBgColor.value = 'feedBackDanger'
		return `已经过期了${Math.abs(daysUntilExpiration)}天`
	} else if (daysUntilExpiration === 0) {
		statesBgColor.value = 'feedBackDanger'
		return `已经过期了`
	} else {
		statesBgColor.value = 'feedBackWran'
		return `${daysUntilExpiration}天后超期`
	}
	console.log('此时的粗无是', statesBgColor.value)
}
// 文件类型过滤
const filterDocument = (type)=>{
	// （1 检察建议书 2 检察意见书 3 磋商文书）
	const documentFile = {"1":"检察建议书","2":"检察意见书","3":"磋商文书"}
	return documentFile[type] || "未知文件"
}
</script>

<style lang="scss" scoped>
.content {
	min-height: 100vh;
	background-color: #f5faff;
	.navs_head {
		height: 20vh;
		/* #ifdef H5 */
		height: 15vh;
		/* #endif */
		padding-bottom: 20rpx;
		background-color: #ffffff;
		position: relative;
		> image {
			position: absolute;
			left: 0;
			top: 0;
			width: 100%;
			height: 100%;
		}
		> text {
			position: absolute;
			left: 32rpx;
			bottom: 120rpx;
			font-weight: normal;
			font-size: 48rpx;
			color: #00041a;
			line-height: 58rpx;
			z-index: 2;
		}
		.tabLoopList {
			width: 100%;
			padding: 0 32rpx;
			position: absolute;
			bottom: 0;
			display: flex;
			.loopItem {
				padding: 25rpx 0;
				font-size: 32rpx;
				color: #686a73;
				font-weight: 500;
				margin-right: 120rpx;
				&:last-child {
					margin-right: 0;
				}
			}
			.item_active {
				color: #00041a;
				position: relative;
				&::after {
					position: absolute;
					bottom: 0;
					left: 50%;
					transform: translateX(-50%);
					content: '';
					width: 48rpx;
					height: 8rpx;
					background: #0d53fe;
					border-radius: 4rpx;
				}
			}
		}
	}
	.tabsList {
		display: flex;
		justify-content: space-between;
		margin: 32rpx;
		> view {
			width: 148rpx;
			height: 64rpx;
			text-align: center;
			line-height: 64rpx;
			background: #ffffff;
			border-radius: 8rpx;
		}
		.tabActive {
			background-color: #0d53fe;
			color: #ffffff;
		}
	}
	.cardList {
		height: calc(80vh - 210rpx);
		padding: 0 35rpx 35rpx;
		.card_title {
			padding-bottom: 35rpx;
			border-bottom: 1rpx solid #f2f6f9;
			font-weight: 600;
			font-size: 24rpx;
			color: #00041a;
			display: flex;
			justify-content: space-between;
			.reciver {
				font-weight: 400;
				font-size: 20rpx;
				color: #bbc0c9;
				background: #fcfcfe;
				border-radius: 4rpx;
				border: 1rpx solid #f2f6f9;
				line-height: 28rpx;
				padding: 4rpx 10rpx;
			}
			.feedBack {
				font-weight: 400;
				font-size: 20rpx;
				background: #fcfcfe;
				border-radius: 4rpx;
				line-height: 28rpx;
				padding: 4rpx 10rpx;
			}
			.feedBackDanger {
				color: #ff4122;
				border: 1rpx solid #ffc0b6;
				background-color: #ffe8e4;
			}
			.feedBackWran {
				color: #fad34a;
				background: #fffdf5;
				border: 1rpx solid #ffecab;
			}
		}
		.card_content {
			padding-top: 35rpx;
			display: flex;
			justify-content: space-between;
			.left {
				display: flex;
				flex-direction: column;
				justify-content: flex-end;
				text {
					&:first-child {
						font-weight: 600;
						font-size: 32rpx;
						color: #00041a;
						line-height: 45rpx;
						margin-bottom: 10rpx;
					}
					&:last-child {
						font-weight: 400;
						font-size: 24rpx;
						color: #686a73;
						line-height: 33rpx;
						margin-bottom: 10rpx;
					}
				}
			}
			.right {
				display: flex;
				align-items: flex-end;
				justify-content: flex-end;
				position: relative;
				.seeDetailBtn {
					font-weight: 400;
					font-size: 28rpx;
					color: #66686a;
					width: 148rpx;
					height: 62rpx;
					text-align: center;
					line-height: 62rpx;
					background: #f7f9fd;
					border-radius: 8rpx;
				}
				.downLoad {
					background: #f0f5ff;
					border-radius: 8rpx;
					width: 148rpx;
					height: 62rpx;
					font-weight: 400;
					font-size: 28rpx;
					color: #0d53fe;
					text-align: center;
					line-height: 62rpx;
					margin-left: 18rpx;
					display: flex;
					align-items: center;
					justify-content: center;
					> image {
						width: 30rpx;
						height: 30rpx;
						margin-right: 5rpx;
					}
				}
				.reciver {
					font-size: 24rpx;
					position: absolute;
					left: 0;
					bottom: 0;
					font-weight: 400;
					font-size: 20rpx;
					color: #bbc0c9;
				}
			}
		}
		.specialDire {
			flex-direction: column;
		}
	}
}
:deep(.uni-popup) {
	> view {
		view {
			padding-bottom: 0 !important;
		}
	}
}
</style>
